import { useKline } from "@/stores/kline";
import { useIndicator } from "@/stores/indicator";
import { useSwitch } from "@/stores/switchBox";

import { URL_BUY_EQUITY, URL_BUY_EQUITY_HOME, URL_CAPITAL_EQUITY, URL_CAPITAL_EQUITY_HOME } from "@/comm/api";
import { get } from "@/comm/request";
import { initChartConfig } from "@/components/chart/config";
import { toMaskData, toTradingViewData } from "@/comm/format";

import {
    Bus,
    CHART_KLINE_SUBSCRIBE,
    CHART_KLINE_SUBSCRIBE_TIME,
    CHART_KLINE__ITEM,
    CHART_KLINE__LIST,
    CONN_BIG_AMOUNT,
    CONN_FLUCTUATION,
    CONN_SIGNAL,
    CONN_STABLE_CURRENCY,
    CONN_STABLE_EVENT,
    INDICATOR_FUNDS,
    INDICATOR_TOGGLE,
    SWITCH_TOGGLE,
    INDICATOR_TREND,
    INDICATOR_WAVE,
    KLINE_CLEAR,
    KLINE_RESET,
    KLINE_RESET_PRICE
} from "@/connetion/Bus";
import { useSignal } from "@/stores/signal";
import { useActivity } from "@/stores/activity";
import { ref, watch, reactive } from "vue";
import i18n from "@/locals";
import { debounce, getFixNum, maskHash } from "@/comm/tooler";
import { formatBigNumber, formatTimestamp } from "@/comm/format";
import { getNearData, getNearTime, getTimer } from "@/components/chart/core/tooler";
import { useRoute } from "vue-router";
import { useAction } from "@/stores/action";
import { useVols } from "@/stores/vols";
import { useTradingView } from "@/stores/tradingVIew";
const { init, registerOverlay, registerFigure, getFigureClass, getSupportedFigures, dispose } = (window as any)["klinecharts"];

export const useComm = function (cid: string, move: any, clickEvent: Function, newspot: any) {
    const kline = useKline();
    const indicator = useIndicator();
    const switchStore = useSwitch();
    const signal = useSignal();
    const activity = useActivity();
    const tradingView = useTradingView()
    const loading = ref(false);
    const route = useRoute();
    const action = useAction();
    const infoId = ref("");
    const vols = useVols();
    let chart: any;
    const overlays: any[] = [];
    // let openIndicator: any[]=[]
    let initMainIndicator: any[] = [];
    let initSubIndicator: any[] = [];
    let initSwitch: any[] = [];
    let maskData: any[] = [];

    const toolTips = ref<any[]>([]);
    let changeTimers: any[] = [];
    let eventList: any[] = [];
    let eventMap: any = {};
    let showMoveBtn = ref(true);
    const infoViewData = reactive({ x: 0, y: 0, opacity: 1 });
    let buSellFlag = true;

    watch(
        () => activity.bigAmounts,
        (newVal: any[], oldVal: any[]) => {
            if (oldVal.length == 0 && newVal.length > 0) {
                let tid = setTimeout(() => {
                    if (chart) {
                        newVal.forEach((i: any) => {
                            // addMark(chart, i, true);
                        });
                    }
                }, 300);
                changeTimers.push(tid);
            }
        }
    );

    function calcFix() {
        let pd = 2;
        let obj = kline.list[0];
        let last = getFixNum(kline.curCoin.lastPrice);
        if (obj) {
            let t1 = getFixNum(obj.open);
            let t2 = getFixNum(obj.close);
            let t3 = getFixNum(obj.high);
            let t4 = getFixNum(obj.low);
            let t5 = getFixNum(kline.curCoin.lastPrice);
            pd = Math.max(t1, t2, t3, t4, t5, last, kline.curCoin.priceDisplayDp, 2);
        }
        else {
            pd = Math.max(kline.curCoin.priceDisplayDp, last, 2);
        }
        chart.setPriceVolumePrecision(pd, 3);
    }

    function addEventListener() {


        Bus.on(KLINE_CLEAR, (val: any) => {
            loading.value = true;
        });

        Bus.on(KLINE_RESET, hideLoading);

        Bus.on(CONN_SIGNAL, (val: any) => {
            addSignalBS(val);
        });

        Bus.on(CHART_KLINE__LIST, (val: any) => {
            console.warn("val", val);
            // const list = val.sort((a: any, b: any) => (a.timestamp > b.timestamp ? 1 : -1));
            const list = val;
            chart.applyNewData(list);
        });

        // Bus.on(CHART_KLINE__ITEM, updateKline);

        Bus.on(CHART_KLINE_SUBSCRIBE_TIME, reset);

        Bus.on(CHART_KLINE_SUBSCRIBE, reset);

        Bus.on(CONN_FLUCTUATION, (val: any) => {
            console.log("链上交易推送", val);
            // if (switchStore.$state.list[0].selected) {
            addMark( val);
            // }
        });

        Bus.on(CONN_STABLE_EVENT, addKlineEvent);

        Bus.on(KLINE_RESET_PRICE, calcFix);
        Bus.on(CONN_BIG_AMOUNT, (val: any) => {
            addMark( val);
        });

        // Bus.on(KLINE_RESET, addHistoryEvent);
        // 判断是否最大值
        function isMax(num: number, array1: Array<number>, array2: Array<number>): boolean {
            if (array1.length === 0 || array2.length === 0) {
                throw new Error("数组为空");
            }
            const max1 = Math.max(...array1);
            const max2 = Math.max(...array2);

            return num > max1 && num > max2;
        }
        function isMin(num: number, array1: Array<number>, array2: Array<number>): boolean {
            if (array1.length === 0 || array2.length === 0) {
                throw new Error("数组为空");
            }
            const min1 = Math.min(...array1);
            const min2 = Math.min(...array2);

            return num < min1 && num < min2;
        }
        window.addEventListener("resize", resizeView);
    }


    async function start() {
        addEventListener();
        // 大额转账交易
        // activity.getEventRange(kline.curCoin.tokenAddress).forEach((i: any) => {
        //     // addMark(chart, i);
        // });

        activity.bigAmounts.forEach((i: any) => {
            // addMark(chart, i);
        });


        // console.log("加载历史记录", res);
        if(kline.curCoin?.tokenAddress){
            activity.loadHistory(kline.curCoin.tokenAddress).then(() => {
                // console.log("加载历史记录", res);
                addHistoryEvent();
            });
        }
        
    }
    function checkBSIdx(loaded: boolean) {
        let item;
        if (loaded) {
            item = indicator.getByValue("CHAIN_BUY");
            if (item) {
                item.selected = true;
                Bus.emit(INDICATOR_TOGGLE, item);
            }

            item = indicator.getByValue("CHAIN_SELL");
            if (item) {
                item.selected = true;
                Bus.emit(INDICATOR_TOGGLE, item);
            }

            // item = indicator.getByValue("SELL");
            // if (item) {
            //     item.selected = true;
            //     Bus.emit(INDICATOR_TOGGLE, item);
            // }
            // item = indicator.getByValue("BUY");
            // if (item) {
            //     item.selected = true;
            //     Bus.emit(INDICATOR_TOGGLE, item);
            // }
        } else {
            item = indicator.getSubByValue("VOL");
            if (item) {
                item.selected = true;
                Bus.emit(INDICATOR_TOGGLE, item);
            }
        }
    }

    function addEvent(aim: any, removeId?: string) {
        let flag = true;
        let item = getNearData(eventList, aim);
        // console.log(aim, eventList, "这是正常的list",removeId,"indexxxxxxx")
        // if (!item) return;
        if (item && eventMap[aim.timestamp]) {
            // console.log("已经存在", eventMap, item.timestamp);
            chart.removeOverlay(eventMap[aim.timestamp]);

            flag = false;
            overlays.map((item: any) => {
                if (item.timestamp == aim.timestamp) {
                    //    chart.removeOverlay(item.id);
                }
            });
        }
        let id = chart.createOverlay({
            name: "event",
            zLevel: 2,
            extendData: {
                data: aim,
                press: false,
                action: !!item ? "more" : aim.char
            },
            points: [
                {
                    timestamp: aim.timestamp,
                    value: aim.high
                }
            ],
            lock: true,
            onRightClick: () => true,
            onClick: (e: any) => {
                console.log("点击---", e);
                let extendData = e.overlay.extendData;
                let list = eventList.filter(i => i.timestamp == aim.timestamp);
                let ary: any[] = [];
                list.forEach(i => {
                    const t = ary.includes((item: any) => item.origin.transactionHash == i.origin.transactionHash);
                    if (!t) {
                        ary.push(i);
                    } else {
                        console.log("重复数据");
                    }
                });
                if (extendData.press) {
                    extendData.press = false;
                    clickEvent(e, ary, false);
                } else {
                    extendData.press = true;
                    // console.log(ary);
                    clickEvent(e, ary, true);
                }
            }
        });

        eventMap[aim.timestamp] = id;

        overlays.push(id);

        eventList.push(aim);
        // console.log("会不会清空呢",eventList)
        return flag;
    }
    function getChartList() {
        return chart && chart.getDataList();
    }
    async function loadBuyData() {
        if (kline.curInterval.name == "S1") return;
        let lastIime = kline.curInterval.name;
        // let item = indicator.getSubByValue("CHAIN_BUY");
        // if((item && item.selected) == false) return;

        let dataList = chart.getDataList();
        let isFirst = dataList.length == 0;

        let ary = isFirst ? kline.list : dataList;

        let type = kline.curInterval.name;
        let startTime = ary[0].timestamp;
        let endTime = ary[ary.length - 1].timestamp;
        let limit = ary.length;

        // 买入净值
        let res: any = await get(URL_BUY_EQUITY_HOME.replace("@", kline.curCoin.tokenAddress || "null"), { type, startTime, endTime, limit }).catch(() => { });
        if (kline.curInterval.name !== lastIime) return;
        let temp = res.data || [];
        temp.forEach((val: any) => {
            let item = ary.find((i: any) => i.timestamp == val.timestamp);
            item && (item.buy = val || {});
        });
        chart.applyNewData(ary);
    }

    async function loadSellData() {
        if (kline.curInterval.name == "S1") return;
        let lastIime = kline.curInterval.name;
        // let item = indicator.getSubByValue("CHAIN_SELL");
        // if((item && item.selected) == false) return;
        let dataList = chart.getDataList();
        let isFirst = dataList.length == 0;
        let ary = isFirst ? kline.list : dataList;
        let type = kline.curInterval.name;
        // let startTime = isFirst ? ary[0].timestamp : ary[ary.length - 30].timestamp;
        let startTime = ary[0].timestamp;
        let endTime = ary[ary.length - 1].timestamp;
        let limit = ary.length;
        // CEX净流出
        let res: any = await get(URL_CAPITAL_EQUITY_HOME.replace("@", kline.curCoin.tokenAddress || "null"), { type, startTime, endTime, limit }).catch(() => { });
        if (kline.curInterval.name !== lastIime) return;
        let temp = res.data || [];
        temp.forEach((val: any) => {
            let item = ary.find((i: any) => i.timestamp == val.timestamp);
            item && (item.sell = val || {});
        });
        chart.applyNewData(ary);
    }
    function end() {
        if (chart) {
            chart.unsubscribeAction("onScroll", resetDiv);
            // chart.unsubscribeAction("onVisibleRangeChange", addInfo);
            chart.unsubscribeAction("onScroll", resNewDiv);
            chart.unsubscribeAction("onVisibleRangeChange", onVisibleRangeChange);
            changeTimers.forEach(i => window.clearTimeout(i));
            // chart && chart.destroy();
            chart.removeIndicator("candle_pane");
            initSubIndicator = indicator.getSubOpen();
            initMainIndicator = indicator.getMainOpen();
            initSwitch = switchStore.getSwitch();

            dispose(chart);
            console.error("##jsz dispose", cid);
        }
        removeEventListener();
    }

    function reset() {
        end();
        start();

    }
    function onVisibleRangeChange(e: any) {
        // console.log("##tom", e)
        if (e.to == chart.getDataList().length) {
            showMoveBtn.value = false;
        } else {
            showMoveBtn.value = true;
        }
    }

    function hideLoading() {
        loading.value = false;
    }

    function updateKline(val: any) {
        if (val.symbol !== kline.curCoin.symbol) {
            console.log("切换延迟数据，抛弃");
            return;
        }
        let t = chart.getDataList();
        chart.updateData(val);
        if (val.done) {
            // 更新净买入净流出;
            let temp = indicator.getSubByValue("CHAIN_BUY");
            if (temp && temp.selected) {
                loadBuyData();
            }

            temp = indicator.getSubByValue("CHAIN_SELL");
            if (temp && temp.selected) {
                loadSellData();
            }
        }
    }
    function addHistoryEvent() {

        let arr = activity.eventList.map(val => {
            // console.log("循环", val)
            return addMark(val);
        });
        // tradingView.upMaskData(arr)
        // debugger
    }

    function addKlineEvent(val: any) {
        addMark( val);
    }

    function resizeView() {
        if (chart) {
            // console.log("--------resize");
            chart.resize();
            resizeChart();
        }

        if (newspot.value) {
            newspot.value.style.visibility = "hidden";
        }
        if (move.value) {
            move.value.style.visibility = "hidden";
        }

        setTimeout(() => {
            resetDiv();
            resNewDiv();
            if (newspot.value) {
                newspot.value.style.visibility = "visible";
            }
            if (move.value) {
                move.value.style.visibility = "visible";
            }
        }, 300);
    }

    function removeEventListener() {
        Bus.off(KLINE_CLEAR);
        Bus.off(KLINE_RESET, hideLoading);
        Bus.off(CONN_SIGNAL);
        Bus.off(CHART_KLINE__LIST);
        Bus.off(CHART_KLINE__ITEM, updateKline);
        Bus.off(CHART_KLINE_SUBSCRIBE_TIME, reset);
        Bus.off(CHART_KLINE_SUBSCRIBE, reset);
        Bus.off(CONN_FLUCTUATION);
        // Bus.off(CONN_BIG_AMOUNT);
        Bus.off(INDICATOR_TREND);
        Bus.off(INDICATOR_TOGGLE);
        Bus.off(CONN_STABLE_EVENT, addKlineEvent);
        Bus.off(SWITCH_TOGGLE);
        Bus.off(KLINE_RESET_PRICE, calcFix);

        // Bus.off(KLINE_RESET, addHistoryEvent);

        window.removeEventListener("resize", resizeView);
    }

    function toggleTrend(val: boolean, chart: any) {
        let ary = chart.getDataList();
        if (val) {
            ary.forEach((i: any) => {
                if (i.trend == 0) {
                    i.color = "#fcc235";
                } else if (i.trend == 1) {
                    i.color = "#0dcb81";
                } else if (i.trend == -1) {
                    i.color = "#f6475d";
                } else {
                    i.color = "#909090";
                }
            });
        } else {
            ary.forEach((i: any) => delete i.color);
        }
        chart.applyNewData(ary);
    }

    function addSignalBS(pot: any) {
        console.log("addSignalBS", pot);
        if (!pot.low) {
            // const ary = chart.getDataList();
            const aim = getNearTime(chart.getDataList(), pot);
            if (!aim) {
                console.log("找不到买卖时间点");
                return null;
            }
            pot.high = aim.high;
            pot.low = aim.low;
            pot.visible = true;
        }

        if (pot.action == "deposit") {
            //充值 红
            pot.color = "#F6475D";
        } else if (pot.action == "withdraw") {
            //提现 绿
            pot.color = "#0DCB81";
        }

        let direction = Number(pot.direction);
        return chart.createOverlay({
            name: "signal",
            extendData: pot,
            points: [
                {
                    timestamp: pot.timestamp,
                    value: direction > 0 ? pot.low : pot.high
                }
            ],
            lock: true,
            onClick: (e: any) => {
                console.log(e);
            }
            // onMouseEnter: onMouseEnter,
            // onMouseLeave: onMouseLeave
        });
    }
    // 震荡信号
    function addSignalShock(pot: any) {
        // console.log("addSignalBS", pot);
        // if (!pot.low) {
        //     // const ary = chart.getDataList();
        //     const aim = getNearTime(chart.getDataList(), pot);
        //     if (!aim) {
        //         console.log("找不到买卖时间点");
        //         return null;
        //     }
        //     pot.high = aim.high;
        //     pot.low = aim.low;
        //     pot.visible = true;
        // }

        // if (pot.action == "deposit") {
        //     //充值 红
        //     pot.color = "#F6475D";
        // } else if (pot.action == "withdraw") {
        //     //提现 绿
        //     pot.color = "#0DCB81";
        // }
        if (!pot.shockSignal) {
            return;
        }
        let direction = Number(pot.shockSignal);
        return chart.createOverlay({
            name: "StockSignal",
            extendData: pot,
            points: [
                {
                    timestamp: pot.timestamp,
                    value: direction > 0 ? pot.low : pot.high
                }
            ],
            lock: true,
            onClick: (e: any) => {
                console.log(e);
            }
            // onMouseEnter: onMouseEnter,
            // onMouseLeave: onMouseLeave
        });
    }

    // 趋势信号
    function addSignalBSCopy(pot: any) {
        // console.log("addSignalBS", pot);
        // if (!pot.low) {
        //     // const ary = chart.getDataList();
        //     const aim = getNearTime(chart.getDataList(), pot);
        //     if (!aim) {
        //         console.log("找不到买卖时间点");
        //         return null;
        //     }
        //     pot.high = aim.high;
        //     pot.low = aim.low;
        //     pot.visible = true;
        // }

        // if (pot.action == "deposit") {
        //     //充值 红
        //     pot.color = "#F6475D";
        // } else if (pot.action == "withdraw") {
        //     //提现 绿
        //     pot.color = "#0DCB81";
        // }
        if (!pot.signal) {
            return;
        }
        let direction = Number(pot.signal);
        return chart.createOverlay({
            name: "signal",
            extendData: pot,
            points: [
                {
                    timestamp: pot.timestamp,
                    value: direction > 0 ? pot.low : pot.high
                }
            ],
            lock: true,
            onClick: (e: any) => {
                console.log(e);
            }
            // onMouseEnter: onMouseEnter,
            // onMouseLeave: onMouseLeave
        });
    }
    function addMark(val: any, immediately = false) {
        let title = "";
        let up = false;
        // val.high = val.high;
        val.timestamp = (val.timestamp || 0) / 1000;

        // if (immediately) {
        //     let id = addPot(val);
        //     overlays.push(id);
        //     return;
        // }

        let act = "in";

        if (val.type == "transfer") {
            if (val.action == "withdraw") {
                //提现
                title = "withdraw";
                act = "out";
                up = true;
            } else if (val.action == "deposit") {
                //充值
                title = "deposit";
                act = "out";
                up = false;
            }
            //普通转账
            else {
                title = "transfer";
                act = "out";
                up = false;
            }
        } else {
            if (val.action == "buy") {
                //买
                title = "buy";
                act = "in";
                up = true;
            } else if (val.action == "sell") {
                //卖
                title = "sell";
                act = "out";
                up = false;
            } else {
                title = "sell";
                act = "out";
                up = false;
            }
        }
        // maskData.push(toMaskData({ ...val, origin: val, char: title[0] }))
        // tradingView.upMaskData()
        //买 in
        //卖 out
        tradingView.upMaskData([toMaskData({ ...val, origin: val, char: title[0], sub: title  })])

        // return toMaskData({ ...val, origin: val, char: title[0] })
        return
        let gg: any = addEvent({ ...val, origin: val, char: title[0] });
        if (!gg) {
            return;
        }
        // console.log("开始绘制", aim)
        let fg = chart.createOverlay({
            name: "action",
            zLevel: 999,
            extendData: {
                title: title,
                sub: `${formatBigNumber(val[act + "Amount"])}`, //(${val[act + "Symbol"]})
                up: up,
                data: val,
                origin: val
            },
            points: [
                {
                    timestamp: val.timestamp,
                    value: val.high
                }
            ],
            lock: true,
            onClick: (e: any) => {
                console.log(312313131312)
                console.log(e);

                console.log("点击---", e);
                let extendData = e.overlay.extendData;
                let list = eventList.filter(i => i.timestamp == val.timestamp);
                let ary: any[] = [];
                list.forEach(i => {
                    const t = ary.includes((item: any) => item.origin.transactionHash == i.origin.transactionHash);
                    if (!t) {
                        ary.push(i);
                    } else {
                        console.log("重复数据");
                    }
                });
                if (extendData.press) {
                    extendData.press = false;
                    clickEvent(e, ary, false);
                } else {
                    extendData.press = true;
                    // console.log(ary);
                    clickEvent(e, ary, true);
                }


                // chart.removeOverlay(fg)
            },
            onMouseEnter: (e: any) => {
                // console.log(e, "enter")
            },
            onMouseLeave: (e: any) => {
                // console.log(e, "leave")
            }
        });
        overlays.push(fg);

        // let tid = setTimeout(() => {
        //     chart.removeOverlay(fg);
        //     let id = addPot(val);
        //     overlays.push(id);

        //     let n = changeTimers.indexOf(tid);
        //     if (n != -1) {
        //         changeTimers.splice(n, 1);
        //     }
        // }, 60000);

        // changeTimers.push(tid);
    }

    function onMove() {
        const ary = chart.getDataList();
        // console.log(ary, "move");
        chart.scrollToTimestamp(ary[ary.length - 1].timestamp, 900);
    }
    function resNewDiv() {
        let t: any = document.getElementById(cid)?.querySelector("canvas");
        if (t && newspot.value) {
            newspot.value.style.left = t.clientWidth - 78 + "px";
            newspot.value.style.top = t.clientHeight - 40 + "px";
        }
    }
    function resetDiv(data: any = null) {
        // console.log("scroll====", data)
        let t: any = document.getElementById(cid)?.querySelector("canvas");
        if (t && move.value) {
            move.value.style.left = t.clientWidth - 40 + "px";
            move.value.style.top = t.clientHeight - 40 + "px";
        }
    }
    function getYAxisWidth() {
        let num = 0;
        let temp: any = document.getElementById(cid)?.querySelectorAll("canvas");
        if (temp) {
            [...temp].forEach(i => {
                if (i.width / i.height < 0.5) {
                    num = i.width;
                }
            });
        }
        return num;
    }

    function checkInit() {
        return !!chart;
    }

    function resizeChart() {
        setTimeout(() => {
            chart && chart.resize();
        }, 300);

        setTimeout(() => {
            chart && chart.executeAction("onZoom");
        }, 900);

        setTimeout(() => {
            chart && chart.executeAction("onScroll");
        }, 1200);
    }

    function addInfo(pot: any) {
        if (infoId.value) {
            chart.removeIndicator("candle_pane", infoId.value);
        }
        // console.error("addInfo pot", pot);
        infoId.value = chart.createIndicator(
            {
                name: "INFORMATION",

                draw: (param: any) => {
                    let { xAxis, kLineDataList, ctx } = param;
                    const width = 20;
                    const height = 20;
                    let last = kLineDataList[kLineDataList.length - 1];
                    // let x = xAxis.convertTimestampToPixel(last.timestamp);
                    // let y = ctx.canvas.height / window.devicePixelRatio - height / 2 - 30;
                    let x = ctx.canvas.width - 30;
                    let y = ctx.canvas.height / window.devicePixelRatio - height / 2 - 70;
                    // console.log('改变poit&&&&&&&&&&&&&', x, y)
                    let r = width / 2;
                    ctx.setLineDash([]);
                    ctx.strokeStyle = "#7E7467";
                    ctx.fillStyle = "rgba(0, 0, 0, 0.1)";
                    ctx.beginPath();
                    ctx.arc(x, y, r, 0, (360 * Math.PI) / 180, false);
                    // ctx.stroke();
                    ctx.fill();

                    pot.x = x;
                    pot.y = y;
                    pot.opacity = x > ctx.canvas.width - 20 ? 0.1 : 1;
                    return false;
                }
            },
            true,
            { id: "candle_pane", axisOptions: { scrollZoomEnabled: false } }
        );
        // console.log('addInfo pot', infoId.value)
        // console.error("addInfo pot tid", infoId.value);
    }

    return { loading, toolTips, start, end, reset, resizeView, onMove, checkInit, getYAxisWidth, resizeChart, getChartList, showMoveBtn, infoViewData, newspot };
};

const calcVRVP = function (candles: any[], count: number) {
    let lower = Math.min(...candles.map(x => x.low));
    let higher = Math.max(...candles.map(x => x.high));
    // const count = 30;
    const ary = [];
    const priceStep = (higher - lower) / count;
    for (let i = 0; i < count; i++) {
        const sp = i * priceStep + lower;
        const ep = sp + priceStep;
        let item = { t: 0, b: 0, s: 0, p: 0 };
        candles.forEach(kline => {
            let n = (kline.open + kline.close) / 2;
            if (n >= sp && n < ep) {
                item.t += kline.volume;
                if (kline.open > kline.close) {
                    item.b += kline.volume;
                } else {
                    item.s += kline.volume;
                }
                item.p = sp;
            }
        });
        ary.push(item);
    }
    return ary;

    // 统计价格区间内的成交量
    // const volumeProfile = _.reduce(
    // 	candles,
    // 	(result, kline) => {
    // 		const price = (kline.open + kline.close) / 2; // 使用开盘价和收盘价的平均值作为价格
    // 		if (price >= priceRange[0] && price <= priceRange[1]) {
    // 			const volume = kline.volume;
    // 			result[price] = (result[price] || 0) + volume;
    // 		}
    // 		return result;
    // 	},
    // 	{}
    // );
    // vrvpDict.value = volumeProfile;
    // console.log('vrvp', volumeProfile)
};
